﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LingHaoSqlScriptHelperTool
{
    public static class Helper
    {
        public static string Is根据类类型处理值(string type, string value)
        {
            if (value == "")
            {
                return "NULL";
            }
            type = type.ToLower();
            var types = new List<string>() { "nvarchar", "datetime", "varchar" };
            if (types.Contains(type))
            {
                if (value.Contains("'"))
                {
                    value = value.Replace("'", "''");
                }
                return $"'{value}'";
            }
            else if (type == "bit")
            {
                return value.ToLower() == "false" ? "0" : "1";
            }
            return value;
        }

        public static string Get截取表名(string sql)
        {
            try
            {
                string normalizedSql = sql.Trim().ToUpper();

                // 正则表达式匹配 FROM 后的表名（支持带架构名如dbo.的情况）
                // 匹配规则：FROM 关键字后跟随的表名（可能包含架构名）
                var match = Regex.Match(normalizedSql,
                    @"\bFROM\b\s+([\w\[\]]+\.)?([\w\[\]]+)",
                    RegexOptions.IgnoreCase);

                if (!match.Success)
                    return "";

                // 提取表名部分（去除可能的方括号） 
                string tableName = match.Groups[2].Value;
                tableName = tableName.Replace("[", "").Replace("]", "");

                return tableName;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public static string 生成Insert语句(TableInfo tableInfo)
        {
            var tableName = tableInfo.TableName;
            tableName = tableName.StartsWith("dbo.") ? tableName : "dbo." + tableName;
            var tabledatas = tableInfo.TableDatas;
            var indexs = tabledatas.Select(x => x.index).Distinct().ToList();
            var sqlall = $"SET IDENTITY_INSERT {tableName} ON \r\n";

            Parallel.For(0, indexs.Count, f =>
            {
                var datas = tabledatas.Where(x => x.index == f + 1).ToList();
                var sql = $"INSERT {tableName} (";
                var sqldata = "(";
                foreach (var item in datas)
                {
                    sql += $"{item.Name},";
                    sqldata += $"{item.Value},";
                }
                sql = sql.TrimEnd(',') + ") VALUES ";
                sql = sql + sqldata.TrimEnd(',') + "); \r\n";
                sqlall += sql;
            }); 
            sqlall += $"SET IDENTITY_INSERT {tableName} OFF \r\n";
            return $"--表名：{tableName} \r\n--生成时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss} \r\n--总行数：{indexs.Count()}\r\n" + sqlall;
        }

        public static void 生成脚本(string filePath, string content)
        {
            using (StreamWriter streamWriter = new StreamWriter(filePath, true))
            {
                streamWriter.WriteLine(content);
            }
        }

        public static bool IsNullOrWhiteSpace_Lh(this string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
